package org.example.ideavr.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.example.ideavr.common.constant.AutoFillConstant;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Slf4j
@Component
public class AutoFillAspect {

    //切点
    @Pointcut("execution(* org.example.ideavr.mapper.*.*(..)) && @annotation(org.example.ideavr.annotation.AutoFill)")
    public void autoFillPointCut(){}

    //前置通知，公共字段补充
    @Before("autoFillPointCut()")
    public void autoFIll(JoinPoint joinPoint){
        log.info("公共字段自动填充...");

        //获取拦截到的方法的对象
        Object[] args = joinPoint.getArgs();
        if(args == null || args.length == 0){
            return;
        }
        Object entity = args[0];

        //准备赋值数据
        LocalDateTime now = LocalDateTime.now();

        //赋值
        try {
            Method setCreateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
            Method setUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);

            setUpdateTime.invoke(entity, now);
            setCreateTime.invoke(entity, now);

        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }



}
